package com.kgc.controller;

import com.kgc.entity.User;
import com.kgc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//Controller受springmvc容器管理,可以将spring容器管理的对象注入进来
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;//注入子容器中的userService

    @RequestMapping("list")
    public String listUser(ModelMap map){
          map.put("list",userService.findAll());
          return "list";
    }

    @RequestMapping("/insert")
    public String insertUser(User user){
        userService.insert(user);
        return "redirect:/user/list";
    }

    @RequestMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") int id){
        userService.delete(id);
        return "redirect:/user/list";
    }

    @RequestMapping("/update")
    public String updateUser(User user){
        userService.update(user);
        return "redirect:/user/list";
    }

    @RequestMapping("/find")
    @ResponseBody
    public User findById(int id){
        User user = userService.findById(id);
        return user;
    }
}
